from flask import Flask, render_template, redirect, url_for, request
import pymysql

app = Flask(__name__)

# MySQL 配置
MYSQL_HOST = 'mysql_db'  # 使用 docker-compose 中的服务名作为 host
MYSQL_USER = 'root'
MYSQL_PASSWORD = 'root'
MYSQL_DB = 'health_db'

# 连接 MySQL 数据库
def get_db_connection():
    return pymysql.connect(
        host=MYSQL_HOST,
        user=MYSQL_USER,
        password=MYSQL_PASSWORD,
        database=MYSQL_DB
    )

# 入口页面：log.html
@app.route('/')
def log():
    return render_template('log.html')

# 路由：index 页面
@app.route('/index')
def index():
    return render_template('index.html')

# 路由：community 页面
@app.route('/community')
def community():
    return render_template('community.html')

# 路由：contact 页面
@app.route('/contact')
def contact():
    return render_template('contact.html')

# 路由：health-analysis 页面
@app.route('/health-analysis')
def health_analysis():
    return render_template('health-analysis.html')

# 路由：health-data 页面
@app.route('/health-data', methods=['GET', 'POST'])
def health_data():
    connection = get_db_connection()

    if request.method == 'POST':
        # 获取表单数据
        item = request.form['item']
        value = request.form['value']
        date = request.form['date']
        
        # 将数据插入数据库
        cursor = connection.cursor()
        cursor.execute('INSERT INTO health_records (item, value, date) VALUES (%s, %s, %s)', (item, value, date))
        connection.commit()
        cursor.close()

    # 获取所有记录
    cursor = connection.cursor()
    cursor.execute('SELECT * FROM health_records')
    records = cursor.fetchall()
    cursor.close()

    connection.close()

    return render_template('health-data.html', records=records)

# 路由：personal-advice 页面
@app.route('/personal-advice')
def personal_advice():
    return render_template('personal-advice.html')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
